package study.thread.atomic;

import java.util.concurrent.atomic.AtomicLong;

/*
 * 用原子量的特性实现取款操作的原子性
 */
public class AtomicAccount {
	private AtomicLong balance;

	public AtomicAccount(long money) {
		balance = new AtomicLong(money);
		System.out.println("Total Money: " + balance);
	}

	public void deposit(long money) {
		balance.addAndGet(money);
	}

	public void withdraw(long money, int delay) {
		long oldValue = balance.get();

		if (oldValue >= money) {
			try {
				//睡眠delay毫秒，模拟多线程并发的情况
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			Boolean flag = balance.compareAndSet(oldValue, oldValue-money);

			if (flag == true) {
				System.out.println(Thread.currentThread().getName()
						+ " withdraw " + money + " successfully ! "
						+ "balance= " + balance);
			} else {
				System.out.println(Thread.currentThread().getName()
						+ " withdraw " + money + " failed ! " + "balance= "
						+ balance);
			}
		} else {
			System.out.println(Thread.currentThread().getName()
					+ " balance is not enough. withdraw failed ! balance="
					+ balance);
		}
	}
}
